package com.cdu.controller;

import com.cdu.commons.MallConstants;
import com.cdu.commons.R;
import com.cdu.commons.ServiceCode;
import com.cdu.commons.ServiceException;
import com.cdu.pojo.dto.FavoriteDTO;
import com.cdu.pojo.dto.TokenUser;
import com.cdu.pojo.entity.Favorite;
import com.cdu.service.FavoriteService;
import com.cdu.util.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@Slf4j
@RequestMapping("/api/favorite")
public class FavoriteController {

    @Autowired
    private FavoriteService favoriteService;

    @GetMapping("/list")
    public R<List<Favorite>> getFavoriteList(Integer page, Integer pageSize, HttpServletRequest request) {
        //获取TOKEN
        String token = request.getHeader(MallConstants.TOKEN_SIGN);
        if (token==null) {
            throw new ServiceException("请先登录", ServiceCode.ERROR_TOKEN);
        }
        //解析token
        TokenUser tokenUser = JwtUtils.getTokenUser(token);
        List<Favorite> favoritesList = favoriteService.getFavoriteList(tokenUser, page, pageSize);
        return R.ok("获取收藏列表成功", favoritesList);
    }


    //取消收藏
    @GetMapping("/cancel")
    public R<String> cancelFavorite(Integer productId, HttpServletRequest request) {
        //获取TOKEN
        String token = request.getHeader(MallConstants.TOKEN_SIGN);
//        if (token==null) {
//            throw new ServiceException("请先登录", ServiceCode.ERROR_TOKEN);
//        }
        //解析token
        TokenUser tokenUser = JwtUtils.getTokenUser(token);
        //打印tokenUser
        log.info("tokenUser:{}", tokenUser);
        favoriteService.cancelFavorite(tokenUser, productId);
        return R.ok("取消收藏成功");
    }


}
